﻿using FZKJ.COMMON;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;

namespace FZKJ.ZHXJ.Models
{
    public class SendMessageCode
    {
        /// <summary>
        /// 外部调用接口发送短信
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="type">1为注册，2为登陆</param>
        /// <returns></returns>
        public static ResultInfo SendByInterface(string mobile, int type)
        {
            var result1 = new ResultInfo(false);

            int code = new Random().Next(10000, 99999);
            string content = "【正航兴救】发送验证码" + code + ",十分钟有效";
            string result = SendSms(code.ToString(), mobile, content);
            var obj = XmlHelper.DeserializeToObject<SmsModel>(result);
            result1.IsSucceed = obj.returnstatus.ToLower() == "success";
            result1.Message = obj.message;
            if ("账户余额不足，请充值！" == obj.message)
            {
                result1.IsSucceed = false;
                result1.Message = "商户短信不足，请联系商家充值短信！";
            }
            if (result1.IsSucceed)
            {
                var model = new Model.buss_smsinfo
                {
                    id = Guid.NewGuid().ToString().ToLower(),
                    mobile = mobile,
                    validatecode = code.ToString(),
                    smscontent = content,
                    createtime = DateTime.Now,
                    deadtime = DateTime.Now.AddMinutes(10),
                    type = type
                };
                result1.token = model.id;
                new BLL.buss_smsinfo().Add(model);
                result1.IsSucceed = true;
                result1.Message = "发送成功！";
            }
            return result1;
        }
        private static string SendSms(string code,string mobile,string content1)
        {
            string url = ConfigurationManager.AppSettings["sendCode"];
            string timestamp = CommonUtils.GetTimeStamp();
            string name = ConfigurationManager.AppSettings["name"];
            string pwd = ConfigurationManager.AppSettings["pwd"];
            string id = ConfigurationManager.AppSettings["id"];
            string sign = EncryptHelper.GetMD5(name + pwd + timestamp).ToLower();
            string content = get_uft8(content1);
            string para = $"action=send&userid={id}&timestamp={timestamp}&sign={sign}&mobile={mobile}&content={content}&sendTime=&extno=";
            string result = HttpClient.HttpPost(url + "?" + para, "");
            return result;
        }
        private static string get_uft8(string unicodeString)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(unicodeString);
            String decodedString = utf8.GetString(encodedBytes);
            return decodedString;
        }
    }
}